
#include "vty_manager.hpp"
#include <linux/types.h>
#include "vty_session.hpp"
#include "command_manager.hpp"

vty_manager_ptr vty_manager::_instance;
boost::mutex vty_manager::_singletone_lock;

vty_manager_ptr 
vty_manager::instance() 
{
    if (_instance.use_count() == 0) {
        boost::mutex::scoped_lock scoped_lock(_singletone_lock);
        if (_instance.use_count() == 0) 
            _instance.reset(new vty_manager());
    }
    return _instance;
};

io_session_ptr
vty_manager::create_session(io_service& ios)
{
    vty_session_ptr ptr(new vty_session(_vty_num++, ios, 
                *(vty_manager::instance()),
                *(command_manager::instance())
                ));
    return ptr;
}

vty_ptr vty_manager::find_vty(__u32 vty_id)
{
    return (vty_ptr)(_sessions[vty_id]);    /* FIXME */
}

void vty_manager::join(vty_session_ptr s) 
{
    PDBG("join vty(id=%d)\n", s->id());
    _sessions[s->id()] = s;

    //_sessions.insert(s);
};

void vty_manager::leave(vty_session_ptr s) 
{
    std::map<__u32, vty_session_ptr>::iterator iter = _sessions.find(s->id());
    if (_sessions.end() == iter) {
        PDBG("don't find vty(id=%d)\n", s->id());
        return;
    }
    PDBG("find leave vty(id=%d)\n", s->id());
    _sessions.erase(iter);
}

void vty_manager::stop_all() 
{
    /*
    std::for_each(_sessions.begin(), _sessions.end(),
            boost::bind(&vty_session::stop, _1));
            */
    _sessions.clear();
    _vty_num = 0;
}


void vty_manager::ctrl_alarm(bool onoff)
{
	_alarm_flag = onoff;
}

const std::string& vty_manager::alarm_file_name()
{
	return _alarm_fname;
}

void vty_manager::receive_alram(const std::string& msg)
{
	{
		boost::mutex::scoped_lock scoped_lock(_alarm_lock);
		_alarm_ostream << msg;
		_alarm_ostream.flush();
	}
	if (_alarm_flag == false) return ;

	{
		boost::mutex::scoped_lock scoped_lock(_session_lock);

		session_map_iterator iter = _sessions.begin();
		for (; iter != _sessions.end(); iter++) {
			(*iter).second->receive_alram(msg);
		}
		//std::for_each(_sessions.begin(), _sessions.end(), boost::bind(&vty_session::receive_alram, msg));
	}
}

